﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRSample.Hubs;
using SignalRSample.Models;
using SignalRSample.Services;

namespace SignalRSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHubContext<TestHub> _context;
        private readonly List<UserVm> _users;
        public HomeController(IHubContext<TestHub> context)
        {
            _context = context;

            _users = new List<UserVm>();
            for (int i = 0; i < 100; i++)
            {
                _users.Add(new UserVm($"gainorloss{i}"));
            }
        }
        public IActionResult Index()
        {
            var htmlEncoder = HtmlEncoder.Default;
            var urlEncoder = UrlEncoder.Default;
            return View();
        }
        public async Task<IActionResult> SendAsync(string msg)
        {
            var name = Guid.NewGuid().ToString("N");
            await _context.Clients.All.SendAsync("SayHelloAsync", $"{name}");
            return Ok();
        }
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View(_users);
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public IActionResult RemoveUserById(string id)
        {
            var user = _users.SingleOrDefault(u=>u.Id.Equals(id));
            if (user!=null)
            {
                _users.Remove(user);
            }
            return Json(true);
        }
    }
}
